import React, { useEffect, useState } from 'react';
import { Card, Button, Table, message } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { getUserList, solveUser, forbidUser } from '../../services/user';

type User = {
  userId: number;
  nickName: string;
  loginName: string;
  isDeleted: 0 | 1;
  createTime: string;
};

const UserAdmin = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const fetchData = () => {
    setLoading(true);
    getUserList({
      pageNumber: pagination.current as number,
      pageSize: pagination.pageSize as number,
    }).then((res) => {
      setUsers(res.data.list || []);
      setPagination({
        ...pagination,
        total: res.data.totalCount,
      });
      setLoading(false);
    });
  };

  useEffect(() => {
    fetchData();
  }, [JSON.stringify(pagination)]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleSolve = () => {
    if (selectedRowKeys.length === 0) {
      message.error('请选择项');
      return;
    }
    solveUser(selectedRowKeys).then(() => {
      message.success('解除成功');
      fetchData();
    });
  };

  const handleForbid = () => {
    if (!selectedRowKeys.length) {
      message.error('请选择项');
      return;
    }
    forbidUser(selectedRowKeys).then(() => {
      message.success('禁用成功');
      fetchData();
    });
  };

  const handleForbidUser = (userId: number) => {
    forbidUser([userId]).then(() => {
      message.success('禁用成功');
      fetchData();
    });
  };

  const handleSolveUser = (userId: number) => {
    solveUser([userId]).then(() => {
      message.success('解除成功');
      fetchData();
    });
  };

  const columns: ColumnsType<User> = [
    {
      title: '昵称',
      dataIndex: 'userName',
    },
    {
      title: '登录名',
      dataIndex: 'loginName',
    },
    {
      title: '身份状态',
      render: (_: any, item: User) => {
        return (
          <span style={{ color: item.isDeleted === 0 ? 'green' : 'red' }}>
            {item.isDeleted === 0 ? '正常' : '禁用'}
          </span>
        );
      },
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render: (_: any, item: User) => {
        return (
          <span>
            {item.isDeleted === 0 ? (
              <Button danger onClick={() => handleForbidUser(item.userId)}>
                禁用
              </Button>
            ) : (
              <Button type='primary' onClick={() => handleSolveUser(item.userId)}>
                解除禁用
              </Button>
            )}
          </span>
        );
      },
    },
  ];

  return (
    <Card>
      <div>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleSolve}
          style={{ marginRight: '10px', marginBottom: '10px' }}
        >
          解除禁用
        </Button>
        <Button danger icon={<DeleteOutlined />} onClick={handleForbid}>
          禁用账户
        </Button>
      </div>

      <Table
        columns={columns}
        rowKey={'userId'}
        pagination={{
          ...pagination,
          onChange: (page, pageSize) => {
            setPagination({
              ...pagination,
              current: page,
              pageSize,
            });
          },
        }}
        rowSelection={rowSelection}
        dataSource={users}
        loading={loading}
      />
    </Card>
  );
};

export default UserAdmin;
